import React, { useState, useEffect } from 'react';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Space,
  Upload,
  message,
  Row,
  Col,
  Divider,
} from 'antd';
import {
  PlusOutlined,
  SaveOutlined,
  CloseOutlined
} from '@ant-design/icons';
import useActivitiesStore from '../../store/activities/useActivitiesStore';
import dayjs from 'dayjs';

const { TextArea } = Input;
const { RangePicker } = DatePicker;
const { Option } = Select;

const ActivityForm = ({ activity, onSuccess, onCancel }) => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [loading, setLoading] = useState(false);
  const { createActivity, updateActivity } = useActivitiesStore();

  // 初始化表单数据
  useEffect(() => {
    if (activity) {
      // 编辑模式：填充现有数据
      form.setFieldsValue({
        name: activity.name,
        slug: activity.slug,
        description: activity.description,
        winnerIds: activity.winnerIds || [],
        status: activity.status,
        timeRange: [
          dayjs(activity.startTime),
          dayjs(activity.endTime)
        ]
      });

      // 设置图片列表
      if (activity.images && activity.images.length > 0) {
        const images = activity.images.map((url, index) => ({
          uid: `-${index}`,
          name: `image-${index}`,
          status: 'done',
          url,
        }));
        setFileList(images);
      }
    } else {
      // 新建模式：设置默认值
      form.setFieldsValue({
        status: 'draft'
      });
    }
  }, [activity, form]);

  // 生成 slug
  const handleNameChange = (e) => {
    const name = e.target.value;
    if (!activity && name) {
      // 只在创建模式下自动生成 slug
      const slug = name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-|-$/g, '');
      form.setFieldValue('slug', slug);
    }
  };

  // 处理图片上传
  const handleUploadChange = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  // 图片上传前的验证
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return false;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片大小不能超过 5MB！');
      return false;
    }
    return false; // 返回 false 阻止自动上传
  };

  // 自定义上传
  const customUpload = ({ file, onSuccess }) => {
    // 这里模拟上传，实际应调用上传 API
    setTimeout(() => {
      onSuccess('ok');
    }, 0);
  };

  // 提交表单
  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      // 处理时间范围
      const [startTime, endTime] = values.timeRange;
      const formData = {
        ...values,
        startTime: startTime.format('YYYY-MM-DD HH:mm:ss'),
        endTime: endTime.format('YYYY-MM-DD HH:mm:ss'),
        images: fileList.map(file => file.url || file.response?.url || URL.createObjectURL(file.originFileObj))
      };
      delete formData.timeRange;

      if (activity) {
        // 编辑模式
        await updateActivity(activity.id, formData);
        message.success('活动更新成功');
      } else {
        // 创建模式
        await createActivity(formData);
        message.success('活动创建成功');
      }
      
      onSuccess?.();
    } catch {
      message.error(activity ? '更新失败' : '创建失败');
    } finally {
      setLoading(false);
    }
  };

  // 上传按钮
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  // 模拟会员数据（实际应从 API 获取）
  const memberOptions = [
    { value: 'member_001', label: 'member_001 - 张三' },
    { value: 'member_002', label: 'member_002 - 李四' },
    { value: 'member_003', label: 'member_003 - 王五' },
    { value: 'member_004', label: 'member_004 - 赵六' },
    { value: 'member_005', label: 'member_005 - 钱七' },
    { value: 'member_006', label: 'member_006 - 孙八' },
    { value: 'member_007', label: 'member_007 - 周九' },
  ];

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      autoComplete="off"
    >
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="活动名称"
            name="name"
            rules={[
              { required: true, message: '请输入活动名称' },
              { max: 50, message: '活动名称最多50个字符' }
            ]}
          >
            <Input
              placeholder="请输入活动名称"
              onChange={handleNameChange}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="活动 Slug"
            name="slug"
            rules={[
              { required: true, message: '请输入活动 slug' },
              { 
                pattern: /^[a-z0-9-]+$/, 
                message: 'Slug 只能包含小写字母、数字和连字符' 
              }
            ]}
            tooltip="用于 URL 的唯一标识，只能包含小写字母、数字和连字符"
          >
            <Input 
              placeholder="例如：spring-beer-tasting-2024" 
              disabled={!!activity}
            />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        label="活动描述"
        name="description"
        rules={[
          { required: true, message: '请输入活动描述' },
          { max: 500, message: '活动描述最多500个字符' }
        ]}
      >
        <TextArea
          rows={4}
          placeholder="请输入活动描述"
          showCount
          maxLength={500}
        />
      </Form.Item>

      <Row gutter={16}>
        <Col span={16}>
          <Form.Item
            label="活动时间"
            name="timeRange"
            rules={[{ required: true, message: '请选择活动时间' }]}
          >
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm"
              style={{ width: '100%' }}
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            label="活动状态"
            name="status"
            rules={[{ required: true, message: '请选择活动状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="draft">草稿</Option>
              <Option value="published">已上线</Option>
              <Option value="offline">已下线</Option>
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        label="获奖会员"
        name="winnerIds"
        tooltip="活动结束后可以设置获奖会员，支持多选"
      >
        <Select
          mode="multiple"
          placeholder="请选择获奖会员"
          style={{ width: '100%' }}
          options={memberOptions}
          filterOption={(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          }
        />
      </Form.Item>

      <Form.Item
        label="活动图片"
        tooltip="最多上传5张图片，每张不超过5MB"
      >
        <Upload
          listType="picture-card"
          fileList={fileList}
          onChange={handleUploadChange}
          beforeUpload={beforeUpload}
          customRequest={customUpload}
          maxCount={5}
          multiple
        >
          {fileList.length >= 5 ? null : uploadButton}
        </Upload>
      </Form.Item>

      <Divider />

      <Form.Item>
        <Space>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            icon={<SaveOutlined />}
          >
            {activity ? '保存修改' : '创建活动'}
          </Button>
          <Button
            onClick={onCancel}
            icon={<CloseOutlined />}
          >
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default ActivityForm;